package com.blacktech.dbu.auth.config;

import com.blacktech.dbu.auth.entity.DbuUser;
import com.blacktech.dbu.auth.repository.UserRepository;
import com.blacktech.dbu.core.dict.UserStatus;
import com.blacktech.dbu.core.dict.UserType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

/**
 * 数据初始化器
 *
 * @author Yanyunsong
 */
@Configuration
public class DataInitializer {

    private static final Logger logger = LoggerFactory.getLogger(DataInitializer.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Bean
    @Transactional
    public CommandLineRunner initData() {
        return args -> {
            // 检查是否已有管理员用户
            if (!userRepository.existsByUsername("admin")) {
                createDefaultAdmin();
                logger.info("默认管理员用户创建成功");
            }
        };
    }

    private void createDefaultAdmin() {
        DbuUser admin = new DbuUser();
        admin.setUsername("admin");
        admin.setPassword(passwordEncoder.encode("admin123"));
        admin.setDisplayName("系统管理员");
        admin.setEmail("admin@dbu.com");
        admin.setUserType(UserType.SUPER_ADMIN);
        admin.setStatus(UserStatus.ENABLED);

        userRepository.save(admin);
        logger.info("创建默认管理员用户: admin / admin123");
    }
}